﻿#include "signup.h"
#include "mainwindow.h"
#include "forgetpasswd.h"
#include "signinwindows.h"
#include "ui_signinwindows.h"
#include "networkcommunication.h"

#include <QList>
#include <QtDebug>
#include <QTcpSocket>
#include <QJsonArray>
#include <QByteArray>
#include <QJsonObject>
#include <QMessageBox>
#include <QJsonDocument>
#include <QJsonParseError>

//#ifdef Q_OS_WIN
//    #pragma execution_character_set("utf-8")   //解决 VS编译器下中文乱码
//#endif

signinwindows::signinwindows(QWidget *parent) :
    QMainWindow(parent),
    ui(new Ui::signinwindows)
{
    ui->setupUi(this);

    isInterrupted = false;
    wrongtimes = 0;

    if(!openfile())
    {
        qDebug() << "打开文件失败";
        return;
    }


    net = NetworkConnect::connectserver();
    server = net->getconserver();

    init_interface();

    connect(net, SIGNAL(user_signin(const QByteArray &)),
            this, SLOT(signin_req(const QByteArray &)));
    qDebug() << __LINE__ << "构造函数结束";
}

signinwindows::~signinwindows()
{
    delete ui;
}

void signinwindows::on_pushButton_showpasswd_pressed()
{
    ui->lineEdit_passwd->setEchoMode(QLineEdit::Normal);
}


void signinwindows::on_pushButton_showpasswd_released()
{
    ui->lineEdit_passwd->setEchoMode(QLineEdit::Password);
}

//把文件读取到的信息加到combox和lineEdit当中
void signinwindows::init_interface()
{
    qDebug() << "初始化界面";
    QJsonDocument js = QJsonDocument::fromJson(lastuserfile->readAll());//读取json文件
    QJsonObject obj = js.object();
    QJsonValue username = obj.value("userid");
    QJsonValue passwd = obj.value("passwd");
    bool autosignin = obj.value("autosignin").toBool();

    ui->comboBox_userid->lineEdit()->setText(username.toString());
    ui->lineEdit_passwd->setText(passwd.toString());

    Qt::CheckState isRememberpasswd = obj.value("rememberpasswd").toBool() ? Qt::Checked : Qt::Unchecked;

    ui->checkBox_rememberpasswd->setCheckState(isRememberpasswd);

    if(autosignin)
    {
        signin_timer = new QTimer(this);
        signin_timer->start(3000);
        connect(signin_timer, &QTimer::timeout, this, &signinwindows::on_pushButton_signin_clicked);
        ui->checkBox_autosignin->setCheckState(Qt::Checked);
        this->setWindowTitle("即将在3秒后登录中...");
        ui->pushButton_signin->setEnabled(false);
//        ui->pushButton_signin->setText("取消登录");
//        disconnect(ui->pushButton_signin, &QPushButton::clicked,
//                   this, &signinwindows::on_pushButton_signin_clicked);
//        connect(ui->pushButton_signin, &QPushButton::clicked,
//                                this, &signinwindows::setInterrupt);
//        on_pushButton_signin_clicked();
    }

    //读取用户信息
    while (!historyfile->atEnd())
    {
        QByteArray buf = historyfile->readLine();
        QList<QByteArray> list = buf.split('@');
        ui->comboBox_userid->addItem(list.at(0).trimmed());
    }
}


//打开文件
bool signinwindows::openfile()
{
    historyfile = new QFile("./history.json",this);
    lastuserfile = new QFile("./curuser.json",this);
    if(!historyfile->open(QIODevice::ReadWrite))
    {
        QMessageBox::critical(this, "错误", "无法打开用户历史配置文件");
        return false;
    }
    if(!lastuserfile->open(QIODevice::ReadWrite))
    {
        QMessageBox::critical(this, "错误", "无法打开last配置文件");
        return false;
    }
    return true;
}

void signinwindows::on_checkBox_autosignin_stateChanged(int arg1)
{
   if(arg1 == Qt::Checked)
   {
        ui->checkBox_rememberpasswd->setCheckState(Qt::Checked);
   }
}

/*
 * 网络通信全程使用json文件信息交流
 * 登录json信息格式
 * {
 * 	"command" : "user_signin",
 * 	"userid" : "用户名",
 * 	"passwd"  : "密码"
 * }
 * */
void signinwindows::on_pushButton_signin_clicked()
{
//    if(!net->isServerconnected())
//    {
//        QMessageBox::information(nullptr, "未知错误", "服务器未连接");
//        return;
//    }
    if(sender() == signin_timer)
    {
        signin_timer->stop();
    }
    qDebug() << __LINE__ << "登录中";
    QString userid = ui->comboBox_userid->lineEdit()->text();
    QString passwd = ui->lineEdit_passwd->text();

    QJsonObject signin_obj;
    signin_obj.insert("command", "user_signin");
    signin_obj.insert("userid", userid);
    signin_obj.insert("passwd", passwd);

    QJsonDocument signin_js(signin_obj);

    server->write(signin_js.toJson());

    lastuserfile->close();
    if(!lastuserfile->open(QIODevice::ReadWrite | QIODevice::Unbuffered | QIODevice::Truncate))
    {
        qDebug() << "打开文件失败:" << lastuserfile->errorString();
        return;
    }

    signin_obj.remove("command");

    signin_obj.insert("rememberpasswd", ui->checkBox_rememberpasswd->isChecked());
    signin_obj.insert("autosignin", ui->checkBox_autosignin->isChecked());

    if(!ui->checkBox_autosignin->isChecked() && !ui->checkBox_rememberpasswd->isChecked())
    {
        signin_obj.remove("passwd");
    }

    lastuserfile->write(QJsonDocument(signin_obj).toJson());
}

/*
 * 服务回发消息格式
 *
 * {
 * 	"type" : "user_signin"
 * 	"isallowed" : true,
 * 	"username" : "用户名",
 * 	"sex" : "性别",
 * 	"errmessage: : "" //如果请求不允许将把错误信息一并回传，成功就是空
 * }
 *
 *
 *
 *
 * */

void signinwindows::signin_req(const QByteArray &mess)
{
    qDebug() << __LINE__ <<  "收到信息";
    QJsonDocument req_js = QJsonDocument::fromJson(mess);
//    if(!req_js.isObject())
//    {
//        qDebug() << "接受登录信息错误:" << __FILE__ << __FUNCTION__ << __LINE__;
//        QMessageBox::information(this, "提示", "未知网络错误");
//        return;
//    }

//    if(isInterrupted)
//    {
//        qDebug() << "处理取消登录";
//        isInterrupted = false;
//        QMessageBox::information(this, "取消", "您取消了自动登录");
//        ui->pushButton_signin->setText("登录");
//        disconnect(ui->pushButton_signin, &QPushButton::clicked,
//                    this, &signinwindows::setInterrupt);
//        connect(ui->pushButton_signin, &QPushButton::clicked,
//                    this, &signinwindows::on_pushButton_signin_clicked);
//        QJsonObject obj;
//        obj.insert("command", "cancel_signin");
//        server->write(QJsonDocument(obj).toJson());
//        return;
//    }

    QJsonObject req_obj = req_js.object();
    bool req_isallowed = req_obj.value("isallowed").toBool();

    bool req_isman = req_obj.value("sex").toString() == "man" ? true : false;

    if(req_isallowed)
    {
        qDebug() << __FUNCTION__ << "登录成功";
        MainWindow *w = new MainWindow();

        if(req_isman)
        {
            w->setStyleSheet("QMainWindow{"
                             "border-image: url(:/new/man.png);"
                                "}");
        }
        else
        {
            w->setStyleSheet("QMainWindow{"
                             "border-image: url(:/new/woman.jpg);"
                                "}");
        }

        w->getlabel_id()->setText(req_obj.value("userid").toString());
        w->getlabel_name()->setText(req_obj.value("username").toString());
        w->setAttribute(Qt::WA_DeleteOnClose);
        w->setuserid(w->getlabel_id()->text());
        w->show();
        this->close();
    }
    else
    {
        QMessageBox::information(this, "登录失败", "错误原因"+req_obj.value("errmessage").toString());
        qDebug() << req_js;
        wrongtimes++;
    }

    if(wrongtimes == 3)
    {
        ui->pushButton_signin->setEnabled(false);
        ui->lineEdit_passwd->setEnabled(false);
        ui->comboBox_userid->lineEdit()->setEnabled(false);
    }
}


void signinwindows::on_pushButton_signup_clicked()
{
    signup *s = new signup(this);
    s->setAttribute(Qt::WA_DeleteOnClose);
    s->show();
}


void signinwindows::on_pushButton_forgetpasswd_clicked()
{
    forgetpasswd *w = new forgetpasswd (this);
    w->setAttribute(Qt::WA_DeleteOnClose);
    w->show();
}

//void signinwindows::setInterrupt()
//{
//    qDebug() << "中断登录";
//    isInterrupted = true;
//}

